var express = require('express');
var router=express.Router();
const {request, response} = require("express");
const{ Sequelize,DataTypes } = require('sequelize');
const jwt = require("jsonwebtoken");
const orm = require('../util/connect').orm()

const car = orm.import('../sequelize/models/trans.model');
//查询所有车辆
router.get('/list',function (req, res, next){
    car.findAll()
        .then(result =>{
            if(result !=null){
                res.send({
                    code:200,
                    msg:"查询成功",
                    data:result
                })
            }else{
                res.send({
                    code:401,
                    msg:'订单为空'
                })
            }
        });
})
//根据ID查车辆
router.post('/info',(req, res)=>{
    const car_id = req.body.car_id;
    car.findOne({
        where:{
            car_id:car_id
        },
    }).then(result =>{
        if(result !=null){
            res.send({
                code:200,
                msg:"查询成功",
                data:result
            })
        }else{
            res.send({
                code:402,
                msg:'订单号输入错误'
            })
        }
    });
})
//添加车辆
router.post('/add',(req, res)=>{
    if(req.user['user.identity'] == '普通用户'){
        res.send({
            code:405,
            msg:"您无权限进行此操作",
        })
        return
    }
    console.log(req.body);
    const data = req.body;
    if(data !=null){
        car.create({
            car_states:data.car_states,
            dest_place:data.dest_place,
            origin_place:data.origin_place,
            duration:data.duration
        })
            .then(result =>{
                if(result !=null){
                    res.send({
                        code:200,
                        msg:"添加成功",
                        data:result
                    })
                }else{
                    res.send({
                        code:402,
                        msg:'添加失败'
                    })
                }
            })
    }

})
//删除车辆信息
router.post('/delete',(req,res)=>{
    if(req.user['user.identity'] == '普通用户'){
        res.send({
            code:405,
            msg:"您无权限进行此操作",
        })
        return
    }
    const carId=req.body.car_id;
    car.destroy({where:{car_id:carId}})
        .then(result => {
        if (result != 0){
            res.send({
                code: 200,
                msg: '已成功删除'
            })
        }
        else{
            res.send({
                code: 500,
                msg: '删除失败'
            })
        }
    })
})
// 修改车辆信息
router.post('/update',(req, res)=>{
    if(req.user['user.identity'] == '普通用户'){
        res.send({
            code:405,
            msg:"您无权限进行此操作",
        })
        return
    }
    res.send('update car profile.')
})

module.exports=router;
